<?php
/**
 * 工具类
 *
 * @author Shengzhi Cheung <shengzhizhang@gmail.com>
 */
class Util
{
    /**
     * 生成指定位数的随机字符串
     * @param integer 指定的位数
     * @return string 生成的随机字符串
     */
    public static function genRandomString($len)
    {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
        $string = '';
     
        for ($p = 0; $p < $len; $p++) {
            $string .= $characters[mt_rand(0, strlen($characters) - 1)];
        }
     
        return $string;
    }

    /**
     * 
     */
    public static function genThumbnail($folder, $name, $ext)
    {
    	$im = null;
		$imagetype = strtolower($ext);
		$path = Yii::app()->basePath.'/../uploads/'.$folder.'/'.$name.'.'.$ext;
		if($imagetype == 'gif')
		    $im = imagecreatefromgif($path);
		else if ($imagetype == 'jpg')
		    $im = imagecreatefromjpeg($path);
		else if ($imagetype == 'png')
		    $im = imagecreatefrompng($path);

        CThumb::resizeImage ( 
        $im,Yii::app()->params['mediumThumbWidth'], Yii::app()->params['mediumThumbHeight'],
        Yii::app()->basePath.'/../uploads/'.$folder.'/medium/'.$name.'.'.$ext, $ext);

		CThumb::resizeImage ( 
		$im,Yii::app()->params['smallThumbWidth'], Yii::app()->params['smallThumbHeight'],
		Yii::app()->basePath.'/../uploads/'.$folder.'/small/'.$name.'.'.$ext, $ext);
    }

    /**
     * 删除单个文件
     * @param 文件的路径
     * @param 文件的名称
     */
    public static function deleteSingleFile($dir, $file)
    {
        $dh=opendir($dir);
        $fullpath=$dir.$file;
        unlink($fullpath);
        closedir($dh);
    }

    /**
     * 删除生成的3种尺寸的图片
     * @param 图片的存储路径
     * @param 图片的名称
     */
    public static function deletePictures($dir, $file)
    {
        // 删除大图
        self::deleteSingleFile($dir, $file);

        // 删除中图
        self::deleteSingleFile($dir."medium/", $file);

        // 删除小图
        self::deleteSingleFile($dir."small/", $file);
    }
}